package com.hospital.controller;

import com.hospital.dao.WardStatusDao;
import com.hospital.dao.impl.WardStatusDaoImpl;
import com.hospital.model.DoctorView;
import com.hospital.model.WardStatusView;
import com.hospital.util.LoggerUtil;
import org.slf4j.Logger;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import com.google.gson.Gson;

/**
 * 病房状态管理Servlet
 * 处理查看病房状态信息的请求，包括按科室、楼层等条件查询
 */
@WebServlet("/wardStatus")
public class WardStatusServlet extends HttpServlet {
    /** 日志记录器 */
    private static final Logger logger = LoggerUtil.getLogger();
    
    /** 病房状态数据访问对象，用于查询病房状态信息 */
    private final WardStatusDao wardStatusDao = new WardStatusDaoImpl();
    
    /** JSON转换工具对象，用于处理JSON数据的序列化和反序列化 */
    private Gson gson = new Gson();
    
    /**
     * 处理获取病房状态信息的GET请求
     * @param request HTTP请求对象
     * @param response HTTP响应对象
     * @throws ServletException Servlet异常
     * @throws IOException IO异常
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        response.setContentType("application/json;charset=UTF-8");
        
        try {
            String action = request.getParameter("action");
            DoctorView doctor = (DoctorView) request.getSession().getAttribute("doctor");
            int deptId = doctor.getDeptId();
            
            if ("getFloors".equals(action)) {
                List<Integer> floors = wardStatusDao.findFloorsByDeptId(deptId);
                response.getWriter().write(gson.toJson(floors));
            } else if ("getWards".equals(action)) {
                int floorNum = Integer.parseInt(request.getParameter("floorNum"));
                List<WardStatusView> wards = wardStatusDao.findByDeptIdAndFloor(deptId, floorNum);
                response.getWriter().write(gson.toJson(wards));
            } else {
                List<WardStatusView> allWards = wardStatusDao.findByDeptId(deptId);
                response.getWriter().write(gson.toJson(allWards));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("{\"error\": \"Database error\"}");
        }
    }

    /**
     * 处理更新病房状态的POST请求
     * @param request HTTP请求对象
     * @param response HTTP响应对象
     * @throws ServletException Servlet异常
     * @throws IOException IO异常
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // ... existing code ...
    }
} 